package com.prd.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.prd.config.LoginInterceptor;
import com.prd.dto.OaDepartDTO;
import com.prd.dto.OaDepartStatementDTO;
import com.prd.dto.OaDepartWorkHandoverDTO;
import com.prd.model.LoginUser;
import com.prd.model.OaDepartDO;
import com.prd.mapper.OaDepartMapper;
import com.prd.model.OaDepartStatementDO;
import com.prd.model.OaDepartWorkHandoverDO;
import com.prd.service.OaDepartService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.prd.service.OaDepartStatementService;
import com.prd.service.OaDepartWorkHandoverService;
import com.prd.util.CommonUtil;
import com.prd.util.JsonData;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 离职管理数据表 服务实现类
 * </p>
 *
 * @author lizhaoyi
 * @since 2024-01-01
 */
@Service
@Slf4j
public class OaDepartServiceImpl extends ServiceImpl<OaDepartMapper, OaDepartDO> implements OaDepartService {


    @Autowired
    private OaDepartMapper oaDepartMapper;

    @Autowired
    private OaDepartWorkHandoverService workHandoverService;

    @Autowired
    private OaDepartStatementService departStatementService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    /**
     * 确定并提交审批
     * @param oaDepartDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonData submit(OaDepartDTO oaDepartDTO) {

        LoginUser loginUser = LoginInterceptor.threadLocal.get();

        //生成关联id
        long departId = IdWorker.getId();
        //保存工作交接事项
        List<OaDepartWorkHandoverDTO> workHandoverDTOS = oaDepartDTO.getWorkHandoverDTOS();
        if (!CollectionUtils.isEmpty(workHandoverDTOS)) {
            for (OaDepartWorkHandoverDTO workHandoverDTO : workHandoverDTOS) {
                workHandoverDTO.setDepartId(departId);
                workHandoverDTO.setCreatedBy(loginUser.getName());
                workHandoverDTO.setCreatedTime(LocalDateTime.now());
            }
            workHandoverService.saveBatch(CommonUtil.dtoListTransfer(workHandoverDTOS, OaDepartWorkHandoverDO.class));
        }

        //保存离职声明
        OaDepartStatementDTO statementDTO = oaDepartDTO.getStatementDTO();
        if (statementDTO != null) {
            statementDTO.setDepartId(departId);
            statementDTO.setCreatedBy(loginUser.getName());
            statementDTO.setCreatedTime(LocalDateTime.now());
            departStatementService.save(CommonUtil.dtoTransfer(statementDTO,OaDepartStatementDO.class));
        }

        try {
            //启动工作流
            HashMap<String, Object> map = new HashMap<>(1);
            map.put("starter", loginUser.getName());
            // 开启流程的key，就是流程定义文件里 process 标签的id
            ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oa_depart", map);
            oaDepartDTO.setProcessId(processInstance.getId());
            log.info("创建添加录用通知书流程 processId：{}", processInstance.getId());
            //提交第一个节点
            Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
            map.clear();
            map.put("reviewBy", oaDepartDTO.getReviewBy());
            taskService.complete(task.getId(),map);
        }catch (Exception e){
            e.printStackTrace();
        }
        //保存数据
        oaDepartDTO.setCreatedBy(LoginInterceptor.threadLocal.get().getName());
        oaDepartDTO.setCreatedTime(LocalDateTime.now());
        OaDepartDO oaDepartDO = CommonUtil.dtoTransfer(oaDepartDTO, OaDepartDO.class);
        oaDepartMapper.insert(oaDepartDO);

        return JsonData.buildSuccess();
    }

}
